package com.buy.service.Impl;

import com.buy.dao.InstantBuyDao;
import com.buy.exception.MsgException;
import com.common.domain.InstantBuyItem;
import com.common.domain.InstantBuySuccess;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author Elias
 * @version 1.0
 * @date 2021-06-24 15:27
 * @description
 * @copyright 2021
 */
@Component
public class Consumer {
  @Autowired private RabbitTemplate rabbitTemplate;

  @Autowired private InstantBuyDao instantBuyDao;

  @Transactional(rollbackFor = Exception.class)
  @RabbitListener(queues = "instantBuy")
  @SendTo("instantBuy")
  public String consumeInstantBuy(String msg) {
    try {
      String itemId = msg.substring(0, 36);
      String userName = msg.substring(36, msg.length());
      Date date = new Date();
      instantBuyDao.decreaseItemNum(itemId, date);
      instantBuyDao.insertItemSuccess(new InstantBuySuccess(null, itemId, userName, 0, date));
      InstantBuyItem item = instantBuyDao.selectItem(itemId, date);
      if (item.getNumber() < 0) {
        throw new MsgException("商品已被秒杀完");
      }
      return msg + "SUCCESS";
    } catch (MsgException e) {
      e.printStackTrace();
      return msg + "FAIL";
    }
  }
}
